import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/Login/Index.vue')
    },
    {
      path: '/dashboard',
      name: 'dashboard',
      component: () => import('@/views/Dashboard/Index.vue'),
      children: [
        // 欢迎页
        {
          path: 'welcome',
          name: 'welcome',
          component: () => import('@/views/Dashboard/Welcome/Index.vue')
        },
        // 用户列表
        {
          path: 'user',
          name: 'user',
          component: () => import('@/views/Dashboard/User/Index.vue'),
          children: [
            {
              path: 'index',
              component: () => import('@/views/Dashboard/User/Index/Index.vue')
            }
          ]
        },
        // 电影列表
        {
          path: 'film',
          name: 'film',
          component: () => import('@/views/Dashboard/Film/Index.vue'),
          children: [
            {
              path: 'index',
              component: () => import('@/views/Dashboard/Film/Index/Index.vue')
            }
          ]
        },
        // 影院列表
        {
          path: 'cinema',
          name: 'cinema',
          component: () => import('@/views/Dashboard/Cinema/Index.vue'),
          children: [
            {
              path: 'index',
              component: () => import('@/views/Dashboard/Cinema/Index/Index.vue')
            }
          ]
        },
        // 校园分布
        {
          path: 'college',
          name: 'college',
          component: () => import('@/views/Dashboard/College/Index.vue'),
          children: [
            {
              path: 'index',
              component: () => import('@/views/Dashboard/College/Index/Index.vue')
            }
          ]
        }
      ]
    },
    {
      path: '/:pathMatch(.*)*',
      component: () => import('@/views/NotFound/Index.vue')
    }
  ]
})

export default router

// 设置全局前置路由守卫
router.beforeEach((to, from) => {
  // 获取pinia存储信息
  const loginInfo = JSON.parse(localStorage.getItem('userInfo') as string)

  // 当访问登录页但已有vuex存储信息时, token存在, 说明已登录, 跳转到首页
  if (to.path === '/login') {
    // 针对token进行登录验证
    if (loginInfo) {
      ElMessage({
        message: '已自动登录',
        type: 'success',
        duration: 2000
      })

      //如果有token就重定向到首页, 没有就正常跳转
      return { path: '/dashboard/welcome' }
    }
    // 如果访问的不是登录页
  } else {
    // 判断有没有vuex存储信息, 如果没有token, 则需要先登录
    if (!loginInfo) {
      ElMessage({
        message: '登录过期',
        type: 'warning',
        duration: 2000
      })

      //如果没有token就重定向到登录页, 有就正常跳转
      return { path: '/login' }
    }
  }
})
